package common.subject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import api.doctor.GetSubjectInfo;
import common.Config;

public class Subject
{
	public int id;
	public int type;
	public int userID;
	public String userVoip;
	public int doctorID;
	public String doctorVoip;
	public boolean isActive;
	public String createTime;
	
	/**
	 * 会话类构造函数
	 * @param token 用户token
	 * @throws JSONException
	 * @throws IOException
	 */
	public Subject(String token) throws JSONException, IOException
	{
		setUserLatestSubjectinfo(token);
	}
	
	/**
	 * 会话类构造函数
	 * @param ID 会话ID
	 * @throws JSONException
	 * @throws IOException
	 */
	public Subject(int id) throws JSONException, IOException
	{
		setSubjectInfo(id);
	}
	/**
	 * 设置用户最近一次会话信息
	 * @param token 用户token
	 * @throws JSONException
	 * @throws IOException
	 */
	public void setUserLatestSubjectinfo(String token) throws JSONException, IOException
	{
		JSONObject subjectinfo=new JSONObject(api.app.Subject.get(token)).getJSONObject("Data");
		if (subjectinfo.getBoolean("HasValue"))
		{
			this.id=subjectinfo.getJSONObject("SubjectInfo").getInt("Id");
			this.type=subjectinfo.getJSONObject("SubjectInfo").getInt("SubjectType");
			this.userID=subjectinfo.getJSONObject("SubjectInfo").getInt("UserID");
			this.userVoip=null;
			this.doctorVoip=subjectinfo.getString("VoipAccount");
			this.doctorID=subjectinfo.getJSONObject("SubjectInfo").getInt("ResponsorID");
			this.isActive=subjectinfo.getJSONObject("SubjectInfo").getBoolean("IsActive");
			String createTime = subjectinfo.getJSONObject("SubjectInfo").getString("CreateTime");
			this.createTime = formatDate(createTime, "yyyy-MM-dd'T'HH:mm:ss");
			
		}
	}
	
	public void setSubjectInfo(int id) throws JSONException, IOException
	{
		String token=Config.getValue("Doctor-Test", "token");
		String subId=String.valueOf(id);
		JSONObject subjectinfo=new JSONObject(GetSubjectInfo.get(subId, token)).getJSONObject("Data");
		this.id=id;
		this.type=subjectinfo.getJSONObject("Subject").getInt("SubjectType");
		this.userID=0;
		this.userVoip=subjectinfo.getJSONObject("User").getString("voipAccount");
		this.doctorID=0;
		this.doctorVoip=null;
		
	}
	
	/**
	 * 将日期格式化为yyyy-MM-dd HH:mm:ss格式
	 * @param sourceDate - 格式化前的日期
	 * @param sourceFormat - 格式化前的日期格式
	 * @return 格式化后的日期；如果执行失败，返回null
	 */
	private String formatDate(String sourceDate, String sourceFormat)
	{
		SimpleDateFormat sdf1 = new SimpleDateFormat(sourceFormat);
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date date = sdf1.parse(sourceDate);
			String ret = sdf2.format(date);
			return ret;
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
}
